<script setup lang="ts">
import CdlForm from "@/components/form";
import type {FormTree} from "@/interfaces/components/Form";
import type {FormData, Mode} from "@/interfaces/components/Page";
import type {Base, Vehicle} from "@/interfaces/views/task/task"
import {ref, h, nextTick} from "vue";
import CdlTable from "@/components/table";
import Routing from "@/components/gps/routing.vue"
import type {TableTree} from "@/interfaces/components/Table";
import {createPopup} from "@/utils/createPopup";
import {cloneDeep} from "lodash";
import {useTaskCarInsertApi, useTaskDetailsApi, useTaskInsertApi, useTaskUpdateApi} from "@/api/project/task";
import {router} from "@/router";
import {useRoute} from "vue-router";
import {mergeObjects} from "@/utils/utilities";
import {useProjectNameListApi} from "@/api/project/project";
import {ElMessage} from "element-plus/es";
import {useGetDriverListApi} from "@/api/vehicle/driver";
import {Driver} from "@/interfaces/views/vehicle/driver";

const route = useRoute()
const loading = ref(false)
let isCaptain = ref(false)
if(route.query.id) init()
if(route.query.projectId) initData()

// 基本信息
const baseEl = ref()
const baseFormTree: FormTree<Base & {dateRange: string[]}> = [
    [
      {label: "任务名称", component: "input", prop: "name",
        rule: {required: true, message: "必须填写任务名称", trigger: "blur"}},
      {label: "关联订单", component: "select", prop: "projectId", serviceOptionKey: "projectName",
        optionProps: {label: "name", value: "id"},
        rule: {required: true, message: "必须选择关联的订单", trigger: "change"}, disabled: true},
      {label: "运单收入", component: "input", prop: "revenue", type: "number",
        rule: {required: true, message: "必须填写运单收入", trigger: "blur"}},
    ],
    [
      {label: "货物名称", component: "input", prop: "cargoName",
        rule: {required: true, message: "必须填写货物名称", trigger: "blur"}},
      {label: "货物类型", component: "input", prop: "cargoType",
        rule: {required: true, message: "必须填写货物类型", trigger: "blur"}},
      {label: "交付验收", component: "checkboxGroup", prop: "acceptType", options: [
          {label: "司机装货查验", value: 1},
          {label: "司机卸货查验", value: 2},
        ]},
    ],
    [
      {label: "开始 / 结束日期", component: "datePicker", type: "daterange", prop: "dateRange",
        rule: {required: true, message: "必须填写开始 / 结束日期", trigger: "change"}, labelWidth: 120},
      {},
      {}
    ]
]
const baseFormData = ref<FormData<Base & {dateRange: string[]}>>({
  name: "",
  projectId: "",
  revenue: undefined,
  cargoName: "",
  cargoType: "",
  acceptType: [],
  startTime: "",
  endTime: "",
  routeId: "",
  dateRange: []
})
// 车辆相关
const vehicleTabTree: TableTree<Vehicle> = {
  colRule: [
    {ti: "关联车辆", prop: "car"},
    {ti: "关联司机", prop: "driverName"},
    {ti: "司机手机号", prop: "phone"},
    {ti: "是否是队长", prop: "captain", dict: "overall_yes_or_no"},
    {ti: "趟次额度", prop: "trip"},
    {ti: "剩余额度", prop: "remainder"},
  ],
  control: [
    {name: "额度+", type: "primary", method: (data)=> limitChange(data, 1)},
    {name: "额度-", type: "primary", method: (data)=> limitChange(data, -1)},
    {name: "删除", type: "danger", method: vehicleDelete},
  ]
}
const vehicleData = ref<Vehicle[]>([])
const vehicleFormTree: FormTree<Vehicle> = [
    [
      {label: "司机名称", component: "select", prop: "driverId", serviceOptionKey: "driverList"
        , optionProps: {label: "name", value: "id"}, rule:[{
          required: true, message: '司机姓名不能为空', trigger: 'blur'
        }], placeholder: "请选择一个司机", changeMethod: (val, data, enable) => {
          const driver = driverList.find(item => item.id === val)
          data.phone = driver?.mobile || ""
          data.car = driver?.licensePlate || ""
          // enable["form-item-phone"] = true
          // enable["form-item-car"] = true
        }},
      {label: "是否是队长", component: "radio", prop: "captain", options: [
          {label: "不是", value: 0},
          {label: "是", value: 1}
        ], rule:[{
          required: true, message: '是否是队长不能为空', trigger: 'blur'
        }]}
    ],
    [
      {label: "关联车辆", component: "input", prop: "car", rule:[{
          required: true, message: '关联车辆不能为空', trigger: 'blur'
        }], disabled: true},
      {label: "司机手机号", component: "input", prop: "phone", rule:[{
          required: true, message: '司机手机号不能为空', trigger: 'blur'
        }, {
          pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
          message: '请输入正确电话号码',
        }], disabled: true}
    ],
    [
      {label: "趟次额度", component: "inputNumber", prop: "trip", min: 1
        , rule:[{
          required: true, message: '趟次额度不能为空，且不小于1', trigger: 'blur'
        }]},
    ]
]
const vehicleFormData: FormData<Vehicle> = {
  driverId: "",
  driverName: "",
  phone: "",
  car: "",
  captain: 0,
  trip: 1
}
// 行程相关
const tripEl = ref()
const tripFormTree: FormTree<Base> = [
  [
    {label: "关联路线id", component: "input", prop: "routeId"},
  ],
]
const tripFormData = ref<FormData<Base>>({
  routeId: ""
})

let driverList: Driver[] = []
let excludeIdArr: string[] = []
/**
 * 获取司机列表
 */
function getDriverList(){
  return new Promise((resolve, reject) => {
    useGetDriverListApi().then(res =>{
      const data = res.data.filter((item: any) => !excludeIdArr.includes(item.id))
      driverList = data
      resolve(data)
    })
  })
}

/**
 * 打开司机新增窗口
 */
function openVehicleInsert(){
  vehicleFormTree[0][1].disabled = isCaptain.value
  createPopup("添加关联车辆/司机", h(CdlForm, {
    templateTree: vehicleFormTree,
    model: vehicleFormData,
    init: {"driverList": getDriverList}
  }), "add", VehiclePopupCallBack)
}

/**
 * 司机删除
 * @param data
 */
function vehicleDelete(data: Vehicle){
  useTaskCarInsertApi(data.id as string).then(()=>{
    ElMessage.success("删除成功！")
    excludeIdArr.splice(excludeIdArr.indexOf(data.driverId), 1)
    vehicleData.value = vehicleData.value.filter(item => {
      if(item.driverId !== data.driverId) return true
      if(item.captain) isCaptain.value = false
    })
  })
}
/**
 * 额度加减
 * @param data
 * @param num
 */
function limitChange(data: Vehicle, num: number){
  data.remainder += num
  data.trip += num
}
/**
 * 弹出层回调
 * @param data 数据
 * @param mode 模式
 */
function VehiclePopupCallBack(mode: Mode, data: any){
  switch (mode) {
    case "add":
      data.remainder = data.trip
      excludeIdArr.push(data.driverId)
      data.driverName = driverList.find(item => item.id === data.driverId)?.name
      if(data.captain) isCaptain.value = true
      vehicleData.value.push(data)
      break
  }
}

function openPlanningRoute(){
  createPopup("规划路线", h(Routing, {
    onSubmit: routeingSave,
    edit: true
  }))
}
function routeingSave(routeId: string){
  baseFormData.value.routeId = routeId
}
function getProjectNameList(){
  return new Promise((resolve, reject) => {
    useProjectNameListApi().then(res=>{
      resolve(res.data)
    })
  })
}
/**
 * 提交
 */
async function submit(){
   const base = await baseEl.value.parentSubmit()
   const data: {[key: string]: any} = {}
   if(base.acceptType.length === 2) base.acceptType = 3
   else base.acceptType = base.acceptType[0] || 0
   Object.assign(data, base)
   if(!isCaptain.value) {
     ElMessage.warning("必须分配一个队长！")
     return
   }
   data["cars"] = cloneDeep(vehicleData.value)
  data.startTime = data.dateRange[0]
  data.endTime = data.dateRange[1]
  delete data.dateRange
   if(route.query.id) {
     data.id = route.query.id
     useTaskUpdateApi(data).then(res =>{
       ElMessage.success("修改任务成功！")
       fallbackPage()
     })
   }
   else {
     useTaskInsertApi(data).then(res =>{
       ElMessage.success("新增任务成功！")
       fallbackPage()
     })
   }
}
/**
 * 初始化
 */
function init(){
  loading.value = true
  useTaskDetailsApi(route.query.id as string | number).then(res =>{
    const {cars, routeInfo, waybills, ...rest} = res.data
    mergeObjects(baseFormData.value, rest)
    switch (baseFormData.value.acceptType){
      case 0:
        baseFormData.value.acceptType = []
        break
      case 1:
        baseFormData.value.acceptType = [1]
        break
      case 2:
        baseFormData.value.acceptType = [2]
        break
      case 3:
        baseFormData.value.acceptType = [1, 2]
    }
    vehicleData.value = cars
    cars?.map((item: Vehicle) => {
      if(item.captain) isCaptain.value = true
      excludeIdArr.push(item.driverId)
    })
    mergeObjects(tripFormData.value, rest)
    loading.value = false
  })
}

/**
 * 初始化
 */
function initData(){
  nextTick(()=>{
    baseFormData.value.projectId = route.query.projectId as string
    baseFormData.value.cargoName = route.query.cargoName as string
    baseFormData.value.cargoType = route.query.cargoType as string
  })
}
/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}
</script>

<template>
<el-card style="position: relative" v-loading="loading">
  <button class="back_btn" @click="fallbackPage"></button>
  <h1 class="top_line">基础信息</h1>
  <el-divider></el-divider>
  <CdlForm :model="baseFormData" :template-tree="baseFormTree" ref="baseEl"
           :init="{projectName: getProjectNameList}"></CdlForm>
  <div class="row">
    <h1>关联车辆 / 司机</h1>
    <el-button type="primary" size="small" @click="openVehicleInsert">添加司机</el-button>
  </div>
  <el-divider></el-divider>
  <CdlTable :data="vehicleData" :template-tree="vehicleTabTree" controlFixed :control-width="250"></CdlTable>
  <div class="row" style="margin-top: 15px">
    <h1>行程信息</h1>
    <el-button type="primary" size="small" @click="openPlanningRoute">规划路线</el-button>
  </div>
  <el-divider></el-divider>
  <div v-if="baseFormData.routeId">已规划一条路线：{{baseFormData.routeId}}</div>
  <div class="control">
    <el-button type="success" @click="submit">保存</el-button>
    <el-button>取消</el-button>
  </div>
</el-card>
</template>

